# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import base64
from sqlalchemy import func
import Environment
from web_lib.page import Page
from web_lib.webutils import Response, expose, json, leggiInSessione
from lib.utils import prep2json


@expose('/pg/ac_Organization/<action>')
@expose('/pg/ac_Organization/')
@expose('/pg/ac_Organization')
def anagraficaOrganization(req, action=None):
    """
    """
    from dao.Organization import Organization
    def __show__(req, action=None):
        pageData = {'file': "/pg/ac_Organization"}
        return Page(req).render(pageData)

    def __list__(req, action=None):
        sorting = req.args.get("jtSorting")
        offset = req.args.get("jtStartIndex")
        batchSize = req.args.get("jtPageSize")
        fk_denominazione = req.form.get("fk_denominazione")
        daos = Organization().select(name=fk_denominazione,
                                        batchSize=batchSize,
                                        offset=offset,
                                        orderBy=sorting)
        count = Organization().count(name=fk_denominazione,
                                        batchSize=None)
        item = {
            "Result": "OK",
            "TotalRecordCount": count,
            "Records": prep2json(daos)}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __edit__(req, action=None):
        id = req.form.get("id")
        if id:
            d = Organization().getRecord(id=int(id))
        else:
            d = Organization()

        pageData = {'file': "pg/addedit/ae_organization",
                    "dao": d,
                    }
        return Page(req).render(pageData)

    def __create__update__(req, action=None):
        """Aggiunge una riga alle pesate"""
        id = req.form.get("id")
        if id != "None":
            d = Organization().getRecord(id=int(id))
        else:
            d = Organization()
        d.name = str(req.form.get("name"))
        d.title = str(req.form.get("title"))
        d.description = str(req.form.get("description"))
        d.state = str(req.form.get("state"))
        d.image_url = str(req.form.get("image_url"))
        d.persist()
        url_red = "/pg/ac_Organization/"
        return Page(req).redirect(url_red)


    def __delete__(req, action=None):
        """Cancella una riga"""
        dao_id = int(req.form.get("id"))
        d = Organization().getRecord(id=dao_id)
        try:
            d.delete()
            item = {"Result": "OK", }
        except:
            item = {
                "Result":"ERROR",
                "Message": "Cancellazione riga non riuscita"}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __preview__(req, action=None):
        id = int(req.form.get("id"))
        #salvaInSessione(req, chiave="id_fornitore_selezionato", valore=id)
        d = TipoCategoria().getRecord(id=id)
        pageData = {'file': "/pg/organization",
                    "dao": d}
        return Page(req).render(pageData)

    if leggiInSessione(req, sezione="Main", chiave="schema") is None:
        url_red = "/pg/main"
    elif action == "List":
        return __list__(req, action=action)
    elif action == "show":
        return __show__(req, action=action)
    elif action == "Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action == "Delete":
        return __delete__(req, action=action)
    elif action=="Ordina":
        return __ordina__(req, action=action)
    elif action=="OrdinaSalva":
        return __ordina_salva__(req, action=action)
    elif action == "Preview":
        return __preview__(req, action=action)
    elif action == "Edit":
        return __edit__(req, action=action)
    else:
        return __show__(req, action=action)
